﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ExtendPropertyLib.WPF;
using System.Collections.ObjectModel;
using ExtendPropertyLib;
using ExORMDesginer.Models;
using MaxZhang.EasyEntities.Persistence;
using MaxZhang.EasyEntities.Persistence.SqlMap;

namespace ExORMDesginer.UserControls
{
    public class DatabaseExplorerInfo : BusinessInfoBase<DatabaseExplorerInfo>
    {
        public static ExtendProperty CurrentSqlMapItemProperty = RegisterProperty(v => v.CurrentSqlMapItem);
        /// <summary>
        /// 当前选择的SQL-MAP项
        /// </summary>
        public SqlMapCommand CurrentSqlMapItem { set { SetValue(CurrentSqlMapItemProperty, value); } get { return (SqlMapCommand)GetValue(CurrentSqlMapItemProperty); } }

        /// <summary>
        /// 在文件系统中载入Map文件中的命令列表
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public List<SqlMapCommand> GetMapListForFile(string fileName)
        {
            DbSession.AddMap(fileName);
            return DbSession.sqlMaps.Values.ToList();
        }

        /// <summary>
        /// 清除SQL-MAP数据列表
        /// </summary>
        public void ClearSqlMaps()
        {
            DbSession.sqlMaps.Clear();
        }


        /// <summary>
        /// 得到将SQL-MAP中的语句参数改变后的字符串
        /// </summary>
        /// <param name="sql">SQL-MAP语句</param>
        /// <param name="parameter">改变后的参数</param>
        /// <returns>SQL-MAP语句</returns>
        public string GetStringWithSqlParameterType(string sql , ParameterInfo parameter)
        {
         
            var regex = new Regex(@"#(\w+):(\w+)[,]?(out|input)?#");
            var ms = regex.Matches(sql);
            foreach (Match m in ms)
            {
                if (m.Success) // parameter of word
                {
                    string name = m.Groups[1].Value;
                    if(m.Groups[1].Value == parameter.Name && m.Groups[2].Value != parameter.ParameterType.Value)
                    {
                        string typeName = parameter.ParameterType.Value;
                        string isOutOrInput = string.Empty;
                        if(m.Groups.Count == 4 && !string.IsNullOrEmpty(m.Groups[3].Value))
                        {
                            isOutOrInput = string.Format(",{0}", m.Groups[3].Value);
                        }
                        string parameterString = string.Format("#{0}:{1}{2}#", name, typeName, isOutOrInput);
                        string oldParameterString = sql.Substring(m.Index, m.Length);
                        sql = sql.Replace(oldParameterString, parameterString);
                    }
                }
            }

            return sql;
        }


        /// <summary>
        /// 从SQL语句中得到命令对象的参数列表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<SerializableObservableCollection<ParameterInfo>> GetCommandParameters(string sql)
        {
            var parameters = new SerializableObservableCollection<ParameterInfo>();
            try
            {
                var regex = new Regex(@"#(\w+):(\w+)[,]?(out|input)?#");
                var ms = regex.Matches(sql);
                foreach (Match m in ms)
                {
                    if (m.Success) // parameter of word
                    {
                        SqlMapParameter p = new SqlMapParameter();
                        p.Name = m.Groups[1].Value;
                        string typeName = m.Groups[2].Value;
                        p.Type = Type.GetType("System." + typeName);
                        p.Direction = m.Groups[3].Value == "out"
                                          ? ParameterDirection.Output
                                          : ParameterDirection.Input;


                        parameters.Add(new ParameterInfo()
                        {
                            Name = p.Name,
                            ParameterType =
                                ParametersListBoxInfo.ParameterTypeList.First(pt => pt.Value == typeName)
                        });


                    }
                }
            }catch{}
            return parameters;
        }


        /// <summary>
        /// 将参数信息转换为SQL-MAP参数
        /// </summary>
        /// <param name="parameters">要转换的参数信息</param>
        /// <returns></returns>
        public List<SqlMapParameter> ConvertParametersToMapParameters(IList<ParameterInfo> parameters)
        {
            var mapParameters = new List<SqlMapParameter>(parameters.Count);
            foreach (var p in parameters)
            {
                Type type = Type.GetType("System." + p.ParameterType.Value);
                mapParameters.Add(new SqlMapParameter(){
                                          Name = p.Name, Direction = ParameterDirection.Input, Type =type , Value = p.Value});
            }

            return mapParameters;
        }



    }
}
